from datetime import datetime, date, timedelta
import time
from dateutil.relativedelta import relativedelta
from dateutil.parser import parse

def get_now_str():
    return datetime.now().strftime('%Y-%m-%d %H:%M:%S')

def get_time_str():
    return datetime.now().strftime('%Y%m%d%H%M%S')

def get_month_str():
    return datetime.now().strftime('%Y-%m')

def get_date_str():
    return datetime.now().strftime('%Y-%m-%d')

# 获取前number月份数组
def get_pre_month(number):
    month_list = []
    for i in range(0, number):
        month_list.append(get_last_month(number-i-1))
    return month_list

# 获取年份
def get_year():
    return datetime.now().year

# 获取月份
def get_month():
    return datetime.now().month

# 获取前n天的日期
def get_last_date_str(n):
    now_time = datetime.now()
    yes_time = now_time + timedelta(days=n)
    return yes_time.strftime('%Y-%m-%d')


# 默认返回最近12个月
# 返回的是时间类型
def get_month_list(start_month_str=None, end_month_str=None):
    if start_month_str is None or start_month_str == '':
        start_month_str = get_day_before_month(datetime.now().strftime('%Y-%m-%d'), -11).strftime('%Y-%m')
    if end_month_str is None or end_month_str == '':
        end_month_str = datetime.now().strftime('%Y-%m')

    start_month = datetime.strptime(start_month_str, '%Y-%m')
    end_month = datetime.strptime(end_month_str, '%Y-%m')
    # delta = end_month - start_month
    month_list = []
    curr_month = start_month
    while curr_month <= end_month:
        month_list.append(curr_month)
        curr_month = curr_month + relativedelta(months=1)
    # 这个list的月份顺序是从以前到现在
    return month_list


# 返回的是时间类型
def get_day_list(start_day_str=None, end_day_str=None):

    start_day = datetime.strptime(start_day_str, '%Y-%m-%d')
    end_day = datetime.strptime(end_day_str, '%Y-%m-%d')
    day_list = []
    curr_day = start_day
    while curr_day <= end_day:
        day_list.append(curr_day)
        curr_day = curr_day + relativedelta(days=1)

    return day_list


# 返回的是时间类型, 获取几个月之前的同一天
def get_day_before_month(curr_day_str=None, before_month_num=None):
    if curr_day_str:
        curr_day_time = datetime.strptime(curr_day_str, '%Y-%m-%d')
    else:
        curr_day_time = datetime.now()
    if before_month_num is None:
        before_month_num = 0

    years = curr_day_time.year
    months = curr_day_time.month
    curr_day = date(years, month=months, day=1)
    before_day = curr_day + relativedelta(months=before_month_num)
    return before_day


# 返回的是时间类型，获取包括本月在内的几个月同一天的时间，diff表示前后几天，比如今天16号，diff=-1则返回15号
def get_last_month_same_day(num=None, diff=None):
    if num is None:
        num = 1
    if diff is None:
        diff = 0
    day_list = []
    curr_day_time = datetime.now() + relativedelta(days=diff)
    while (num >= 0):
        new_month_day = curr_day_time - relativedelta(months=num)
        new_month_day = new_month_day.strftime('%Y-%m-%d')
        day_list.append(new_month_day)
        num = num - 1
    return day_list

def get_diff(compare_day_str1=None, compare_day_str2=None):
    if compare_day_str1 is None:
        compare_day_str1 = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    if compare_day_str2 is None:
        compare_day_str2 = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    time_1_struct = datetime.strptime(compare_day_str1, "%Y-%m-%d %H:%M:%S")
    time_2_struct = datetime.strptime(compare_day_str2, "%Y-%m-%d %H:%M:%S")
    seconds = (time_1_struct - time_2_struct).total_seconds()
    print(compare_day_str1 + ' ' + compare_day_str2 + '秒数差值为：' + str(seconds))
    return int(seconds)

# 判断是否闰年
def is_leap(year):
    return year % 4 == 0 and year % 100 != 0 or year % 400 == 0

# 获取某年某月的天数
def get_days(year, month):
    if month in [1, 3, 5, 7, 8, 10, 12]:
        return 31
    elif month == 2:
        return 29 if is_leap(year) else 28
    else:
        return 30

# 获取当季已走完的月份数
def get_months_qua_now():
    ticks = time.localtime(time.time())
    now_month = ticks[1]
    now_qua = int((int(now_month) - 1) / 3) + 1
    return now_month-(now_qua-1)*3
# 获取当前季度 输出2022Q1
def get_qua_now():
    ticks = time.localtime(time.time())
    now_year = ticks[0]
    now_month = ticks[1]
    now_qua = int((int(now_month) - 1) / 3) + 1
    return str(now_year)+"Q"+str(now_qua)

# 获取前一天日期
def get_pre_day():
    now_time = datetime.now()
    yes_time = now_time + relativedelta(days=-1)
    yes_time_nyr = yes_time.strftime('%Y-%m-%d')  # 格式化输出
    return yes_time_nyr

# 获取前一天日期
def get_pre_day_with_param(date_str):
    now_time = datetime.strptime(date_str, '%Y-%m-%d')
    yes_time = now_time + relativedelta(days=-1)
    yes_time_nyr = yes_time.strftime('%Y-%m-%d')  # 格式化输出
    return yes_time_nyr

def get_last_month(number):
    # 获取前几个月
    month_date = datetime.now().date() - relativedelta(months=number)
    return month_date.strftime("%Y-%m")



# 获取当季度已过的月份 返回list
def get_old_month_qua():
    month_ed = get_months_qua_now()
    month_id = datetime.now().strftime("%Y-%m")
    month_list = []
    if month_ed>1:
        for i in range(month_ed):
            if month_id != get_last_month(i):
                month_list.append(get_last_month(i))
    return month_list

def get_last_month_day(number):
    # 当前时间
    month_date = datetime.now().date() - relativedelta(months=number)
    print(month_date.year)
    year = month_date.year
    month = month_date.month
    months = month
    if month<10:
        months ="0"+str(month)
    day = get_days(month_date.year,month_date.month)
    return str(year)+"-"+str(months)+"-"+str(day)


def get_old_month_qua_las_day():
    month_ed = get_months_qua_now()
    month_id = datetime.now().strftime("%Y-%m")
    day_list = []
    if month_ed > 1:
        for i in range(month_ed):
            if month_id != get_last_month(i):
                day_list.append(get_last_month_day(i))
    return day_list

# 获取当天的秒数返回
def get_seconds_days():
    dt = get_date_str()
    ts = int(time.mktime(time.strptime(dt, "%Y-%m-%d")))
    return ts

# month_id 为 yyyy-mm 格式
def get_quarterly_id(month_id):
    temp_month_id = month_id[5:7]
    if 1 <= int(temp_month_id) <= 3:
        return month_id[0:4] + 'Q1'
    if 4 <= int(temp_month_id) <= 6:
        return month_id[0:4] + 'Q2'
    if 7 <= int(temp_month_id) <= 9:
        return month_id[0:4] + 'Q2'
    if 10 <= int(temp_month_id) <= 12:
        return month_id[0:4] + 'Q4'

# 获取两个时间相差的秒数
def js_time(start_time,end_time):
    return (parse(str(end_time)) - parse(str(start_time))).seconds

if __name__ == '__main__':
    lists = get_month_list('2020-03', '2020-06')
    print('xxxxx' + get_last_date_str(11)[0:7])

    curr_day = datetime.now()
    last_day = get_day_before_month(curr_day.strftime('%Y-%m-%d'), -3)
    print(last_day)

    lists = get_month_list(last_day.strftime('%Y-%m'), curr_day.strftime('%Y-%m'))
    print(lists)

    last_day = get_day_before_month(datetime.strftime(curr_day, '%Y-%m-%d'), 3)
    print(last_day)

    lists = get_month_list(datetime.strftime(curr_day, '%Y-%m'), datetime.strftime(last_day, '%Y-%m'))
    print(lists)

    curr_day_str = datetime.now().strftime('%Y-%m-%d')
    print(curr_day_str[0:7])

    lists = get_day_list('2020-10-11', '2020-10-30')
    print(lists)

    print(get_last_month_same_day(3))

    print('2020-12-10'[5:10])

    second = get_diff('2020-01-02 00:00:00', '2020-01-01 00:00:00')
    print(second)

    print(get_now_str())

    print(get_last_month_same_day(3, 0))

    start = datetime.strptime(datetime.now().strftime('%Y-%m-%d') + ' 00:00:00', '%Y-%m-%d %H:%M:%S')
    print('xxxx  ' + str(start))
    end = start + relativedelta(days=1)
    print('xxxx  ' + str(end))

    curr_day_time = datetime.now() + relativedelta(days=-1)
    print(curr_day_time.strftime('%Y-%m-%d'))


    test = {'ddd': None}
    test = {'ddd': ""}
    print(test.get('ddd', "cc"))

    print(test.get('ddd', "cc") if test.get('ddd', "ccc") else "cccc")

    strs = "0123456dfsafd"
    print(strs[1:])

    print(get_qua_now())

    print('---' + get_last_date_str(-1))



